package com.metro.paperless.common.utils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailUtil {

	public static void sendMail(String subject, String content, String to) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"application/applicationContext.xml");
		SendMail mail = (SendMail) context.getBean("simpleMail");
		mail.sendMail(subject, content, to);
	}

	public static void sendHtmlMail(String subject, String content, String to){
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"application/applicationContext.xml");
		// 获取JavaMailSender bean
		JavaMailSenderImpl sender = (JavaMailSenderImpl) ctx
				.getBean("mailSender");
		MimeMessage mailMessage = sender.createMimeMessage();
		MimeMessageHelper messageHelper;
		try {
			messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");
		
		messageHelper.setFrom(sender.getUsername());
		messageHelper.setTo(to);
		messageHelper.setSubject(subject);
		// true 表示启动HTML格式的邮件
		messageHelper.setText(content,true);
		// messageHelper.addInline("image", img);//根cid一致
		sender.send(mailMessage);
		System.out.println("发送给："+to+"的邮件发送成功...");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("发送给："+to+"的邮件发送失败...");
		}
	}

	public static void main(String[] args) throws Exception {
		sendMail("测试邮件标题", "测试邮件内容", "502584966@qq.com");
		//sendHtmlMail("测试邮件标题", "<h1>测试邮件内容</h1><p>测试邮件内容主题</p>","214389303@qq.com");
	}
}
